const socket = io();



const submitBtn = document.querySelector('#submit');

const logoutBtn = document.querySelector('#logout');

const sendBtn = document.querySelector('#sendBtn');

const messageInput = document.querySelector('#messageInput');

const nicknameInput = document.querySelector('#nicknameInput');

const chatWrapper = document.querySelector('#chatroom');

const loginPanel = document.querySelector('#loginPanel');

const avatarImg = document.querySelector('#avatarImg');

const nickname = document.querySelector('#nickname');

const messages = document.querySelector('#messages');

 

let avatar;

 

 

// 提交昵称登录

submitBtn.addEventListener('click', function () {

  const nickname = nicknameInput.value;

  if (nickname.trim().length > 0) {

    avatar = `https://avatars.dicebear.com/api/bottts/${Date.now()}.svg`;

    socket.emit('login', { username: nickname, avatar: avatar });

  } else {

    alert('昵称为空，请重新输入');

    nicknameInput.value = '';

    nicknameInput.focus();

  }

});

 

// 退出登录

logoutBtn.addEventListener('click', function () {

  socket.disconnect();

});

 

// 发送消息

sendBtn.addEventListener('click', function () {

  const msg = messageInput.value.trim();

  if (msg.length > 0) {

    socket.emit('chatMessage', msg);

    messageInput.value = '';

    messageInput.focus();

  }

});

 

// 回车发送消息

messageInput.addEventListener('keyup', function (e) {

  e.preventDefault();

  if (e.keyCode === 13) {

    sendBtn.click();

  }

});

 

// 服务器发送登录信号

socket.on('login', (info) => {

  loginPanel.style.display = 'none';

  chatWrapper.style.display = 'block';

  avatarImg.src = avatar;

  nickname.innerText = nicknameInput.value;

  renderUserList(info.onlineUsers);

});

 

// 服务器发送聊天消息信号

socket.on('chatMessage', (data) => {

  renderChatMessage(data.nickname, data.message);

});

 

// 服务器发送退出信号

socket.on('logout', (info) => {

  renderUserList(info.onlineUsers);

});

 

// 渲染在线用户列表

function renderUserList(users) {

  const list = document.createElement('ul');

  Object.keys(users).forEach((nickname) => {

    const item = `

    <li>

      <img src="${users[nickname]}"/>

      <span>${nickname}</span>

    </li>

    `;

    list.innerHTML += item;

  });

  chatWrapper.insertBefore(list, messages);

}

// 渲染聊天消息
function renderChatMessage(nickname, message) {

  const msg = document.createElement('div');

  msg.innerHTML = `<p>${nickname}: ${message}</p>`;

  messages.appendChild(msg);

}